package com.xiaolun.threadConnect;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


class AirCondition2 {
	private int number = 0;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	public void increment() throws Exception { //制热
		lock.lock();
		try {
			//1、判断
			while (number != 0) {
//				this.wait();
				condition.await();
			}
			//2、干活
			number++;
			System.out.println(Thread.currentThread().getName() + "\t" + number);
			//3、通知
//			this.notifyAll();
			condition.signalAll();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void decrement() throws Exception { //制热
		lock.lock();
		try {
			//1、判断
			while (number == 0) {
				condition.await();
			}
			//2、干活
			number--;
			System.out.println(Thread.currentThread().getName() + "\t" + number);
			//3、通知
			condition.signalAll();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}

/**
 * 题目：现在两个线程，可以操作初始值为零的一个变量，
 * 实现一个线程对该变量加1，一个线程对该变量减1，
 * 实现交替，来10轮，变量初始值为0。
 * 1、高内聚低耦合的前提下：线程操作资源类
 * 2、判断/干活/通知
 * 3、在多线程里面，要防止多线程的虚假唤醒。（乘客二次过安检）
 */
public class ProdConsumerDemo02 {
	public static void main(String[] args) {
		AirCondition2 airCondition = new AirCondition2();

		new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				try {
					airCondition.increment();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, "A").start();
		new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				try {
					airCondition.decrement();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, "B").start();
	}
}
